package com.manner.groupon.schedu;

import com.manner.groupon.model.entity.GrouponCoupons;
import com.manner.groupon.model.entity.GrouponOrder;
import com.manner.groupon.model.enums.OrderStatus;
import com.manner.groupon.service.groupon.GrouponCouponsService;
import com.manner.groupon.service.groupon.impl.GrouponOrderServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Component
@Slf4j
public class CouponExpireScheduling {

    @Resource
    private GrouponOrderServiceImpl grouponOrderService;

    @Resource
    private GrouponCouponsService couponsService;


    @Scheduled(cron = "0 0 1 * * ?")
    public void expire() {
        log.info("------- 定时任务启动 -------");
        //获取所有待使用的订单
        List<GrouponOrder> list = grouponOrderService.query().eq("status", OrderStatus.HAVE_PAID.getCode()).list();
        //判断是否为空
        if (list.isEmpty()) {
            return;
        }
        //不为空,获取订单的优惠券
        for (GrouponOrder order : list) {
            GrouponCoupons coupons = couponsService.query().eq("id", order.getGcId()).one();
            //算出是什么时候过期
            LocalDateTime localDateTime = LocalDateTime.parse(order.getCreateTime(), DateTimeFormatter.ISO_LOCAL_DATE_TIME);
            //加上天数
            LocalDateTime expireTime = localDateTime.plusDays(coupons.getEffectDay());
            //获取现在的日期
            LocalDateTime now = LocalDateTime.now();
            //判断是否处于之后
            boolean after = now.isAfter(expireTime);
            //判断
            if (after) {
                //过期
                order.setStatus(OrderStatus.HAVE_EXPIRED.getCode());
                //修改数据
                grouponOrderService.updateById(order);
            }
            //没过期
        }
    }

}
